package com.ruoyi.whzj.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.CommonRpc;
import com.ruoyi.common.utils.EmptyUtils;
import com.ruoyi.common.utils.IdWorker;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.whzj.domain.*;
import com.ruoyi.whzj.service.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.security.MessageDigest;
import java.util.*;


/**
 * 快手接口控制器
 */
@Controller
@RequestMapping(value = "/phone/whzj/payApi")
public class PayApiController extends BaseController {

    @Autowired
    private IWhUserService whUserService;

    @Autowired
    private IWhTasksettingService whTasksettingService;

    @Autowired
    private IWhzjBaseconfigService whzjBaseconfigService;

    @Autowired
    private IWhBalancerecordService whBalancerecordService;

    @Autowired
    private IWhIntegralHistoryService whIntegralHistoryService;

    @Autowired
    private IWhUserwithdrawService whUserwithdrawService;

    @Autowired
    private IWhMemberlevelService whMemberlevelService;

    @Autowired
    private IWhPointspackageService whPointspackageService;

    @Autowired
    private IWhPayrecordService whPayrecordService;

    @Value("${wxConfig.server_url}")
    private String serverUrl;

    private static String pid = "723660";

    private static String key = "2A151AA3772328B75383638443B92947";

    /**
     * 用户购买积分
     * @param type
     * @param id
     * @param userId
     * @param payType  0购买代理，1购买积分
     * @return
     * @throws Exception
     */
    @RequestMapping("/appPay")
    @ResponseBody
    public AjaxResult testPay(String type, String id, String userId, String payType)throws Exception
    {

        WhUser user = whUserService.selectWhUserById(userId);
        if("0".equals(user.getIsDisable())){
            return error("用户被封禁，请联系客服");
        }
        WhzjBaseconfig baseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");

        WhPointspackage pointspackage = whPointspackageService.selectWhPointspackageById(id);
        BigDecimal package_price = new BigDecimal(baseconfig.getAgentPay().toString());
        if(pointspackage != null){
            package_price = pointspackage.getPackagePrice();
        }


        WhPayrecord payrecord = new WhPayrecord();
        payrecord.setId(IdWorker.getId() + StringUtils.getRandomString(6));
        payrecord.setUserId(userId);
        payrecord.setPackageId(id);
        payrecord.setPayMoney(package_price);
        String name = "积分赞助";
        String money = package_price.toString();
        switch (payType){
            case "0":payrecord.setPayType("购买代理");
                name = "购买代理";
                break;
            case "1":payrecord.setPayType("购买积分");

                break;

        }

        payrecord.setCreateTime(new Date());
        payrecord.setUpdateTime(new Date());
        switch (type){
            case "alipay":payrecord.setPayMethod("支付宝");break;
            case "qqpay":payrecord.setPayMethod("QQ钱包");break;
            case "wxpay":payrecord.setPayMethod("微信");break;
        }
        whPayrecordService.insertWhPayrecord(payrecord);


        String out_trade_no = payrecord.getId();
        String notify_url = serverUrl + "phone/whzj/payApi/paySuccessNotify";
        String return_url = serverUrl + "phone/whzj/payApi/paySuccessReturn";


        SortedMap<Object,Object> parameters= getSortedMapAli(pid,out_trade_no,notify_url,return_url,name,money, type);
        String sign = createSign("UTF-8", parameters);
        System.out.println("sign---------------" + sign);
        String url = "http://ce999.cn/submit.php?pid="+pid+"&type="+type+"&out_trade_no="+out_trade_no+"&notify_url="+notify_url+"&return_url="+return_url+"&name="+name+"&money="+money+"&sign="+sign+"&sign_type=MD5";
        System.out.println("url---------------" + url);
        return success("操作成功", url);

    }

    /**
     * 支付回调
     * @param trade_no 凡起易支付订单号
     * @param out_trade_no 	商户系统内部的订单号
     * @param trade_status 支付状态 TRADE_SUCCESS
     * @param sign 签名字符串
     * @return
     * @throws Exception
     */
    @RequestMapping("/paySuccessNotify")
    @ResponseBody
    public AjaxResult paySuccessNotify(String trade_no, String out_trade_no, String trade_status, String sign)throws Exception
    {
        if(!"TRADE_SUCCESS".equals(trade_status)){
            return error();
        }

        WhPayrecord payrecord = whPayrecordService.selectWhPayrecordById(out_trade_no);
        if(!"0".equals(payrecord.getStatus())){
            return error();
        }
        String userId = payrecord.getUserId();
        WhUser user = whUserService.selectWhUserById(userId);
        payrecord.setUpdateTime(new Date());
        payrecord.setStatus("1");
        whPayrecordService.updateWhPayrecord(payrecord);

        if("购买积分".equals(payrecord.getPayType())){
            String packageId = payrecord.getPackageId();
            WhPointspackage pointspackage = whPointspackageService.selectWhPointspackageById(packageId);
            int point = pointspackage.getPackagePoint();
//            int experience = pointspackage.getGiveExperience();
            int give_point = pointspackage.getGivePoint();
            int give_toptimes = pointspackage.getGiveToptimes();

            WhUser user1 = new WhUser();
            user1.setId(userId);
            user1.setToptimes(user.getToptimes() + give_toptimes);
            user1.setIntegral(user.getIntegral() + point + give_point);
            user1.setExperience(user.getExperience() + give_point);
            WhMemberlevel memberlevel = whMemberlevelService.selectMemberLevelByNumber(user1.getExperience().toString());
            user1.setLevel(memberlevel.getId());

            whUserService.updateWhUser(user1);


            //积分记录
            WhIntegralHistory history = new WhIntegralHistory();
            history.setId(IdWorker.getId());
            history.setCreateTime(new Date());
            history.setUserId(userId);
            history.setIntegral(point + give_point);
            history.setEventId(null);
            history.setOperat("17");
            whIntegralHistoryService.insertWhIntegralHistory(history);

            if(EmptyUtils.isNotEmpty(user.getpCode())){
                WhzjBaseconfig baseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");

                //根据父级邀请码查下父级是否存在
                WhUser userP = whUserService.selectWhUserByCodeId(user.getpCode());
                if(userP != null){
                    double first = Double.valueOf(userP.getCommission());

                    Double balance = pointspackage.getPackagePrice().doubleValue() * first / 100;

                    WhUser userP1 = new WhUser();
                    userP1.setId(userP.getId());
                    userP1.setBalance(new BigDecimal(userP.getBalance().doubleValue() + balance).setScale(2, BigDecimal.ROUND_HALF_UP));
                    userP1.setMoney(new BigDecimal(userP.getMoney().doubleValue() + balance).setScale(2, BigDecimal.ROUND_HALF_UP));

                    whUserService.updateWhUser(userP1);

                    WhBalancerecord balancerecord = new WhBalancerecord();
                    balancerecord.setId(IdWorker.getId());
                    balancerecord.setCreateTime(new Date());
                    balancerecord.setUserId(userP.getId());
                    balancerecord.setBalance(new BigDecimal(balance).setScale(2, BigDecimal.ROUND_HALF_UP));
                    balancerecord.setOperate("1");
                    balancerecord.setYongjinUser(userId);
                    balancerecord.setOrderId(out_trade_no);
                    balancerecord.setFront(userP.getBalance());
                    balancerecord.setAfter(userP1.getBalance());
                    whBalancerecordService.insertWhBalancerecord(balancerecord);

                    if(EmptyUtils.isNotEmpty(userP.getpCode())){

                        //根据父级邀请码查下父级是否存在
                        WhUser userPP = whUserService.selectWhUserByCodeId(userP.getpCode());
                        if(userPP != null){
                            double second = Double.valueOf(userPP.getSecondDistirrate());

                            Double balance2 = pointspackage.getPackagePrice().doubleValue() * second / 100;

                            WhUser userPP1 = new WhUser();
                            userPP1.setId(userPP.getId());
                            userPP1.setBalance(new BigDecimal(userPP.getBalance().doubleValue() + balance2).setScale(2, BigDecimal.ROUND_HALF_UP));
                            userPP1.setMoney(new BigDecimal(userPP.getMoney().doubleValue() + balance2).setScale(2, BigDecimal.ROUND_HALF_UP));

                            whUserService.updateWhUser(userPP1);

                            WhBalancerecord balancerecord2 = new WhBalancerecord();
                            balancerecord2.setId(IdWorker.getId());
                            balancerecord2.setCreateTime(new Date());
                            balancerecord2.setUserId(userPP.getId());
                            balancerecord2.setBalance(new BigDecimal(balance2).setScale(2, BigDecimal.ROUND_HALF_UP));
                            balancerecord2.setOperate("2");
                            balancerecord2.setYongjinUser(userId);
                            balancerecord2.setOrderId(out_trade_no);
                            balancerecord2.setFront(userPP.getBalance());
                            balancerecord2.setAfter(userPP1.getBalance());
                            whBalancerecordService.insertWhBalancerecord(balancerecord2);


                        }
                    }

                }
            }


            return success();
        }else if("购买代理".equals(payrecord.getPayType())){
            WhzjBaseconfig whzjBaseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
            WhUser user1 = new WhUser();
            user1.setId(userId);
            user1.setUserGroup("代理用户");
            if(EmptyUtils.isEmpty(user1.getCommission())){
                user1.setCommission(whzjBaseconfig.getFirstDistrirate().toString());
                user1.setSecondDistirrate(whzjBaseconfig.getSecondDistirrate().toString());
            }
            whUserService.updateWhUser(user1);
            return success();
        }
       return error();
    }


    /**
     * 支付成功还是失败 同步回调
     * @param trade_no
     * @param out_trade_no
     * @param trade_status
     * @param sign
     * @return
     * @throws Exception
     */
    @RequestMapping("/paySuccessReturn")
    public String paySuccessReturn(String trade_no, String out_trade_no, String trade_status, String sign)
    {

        if(!"TRADE_SUCCESS".equals(trade_status)){
            return "whzj/api/fail";
        }
        try {
            WhPayrecord payrecord = whPayrecordService.selectWhPayrecordById(out_trade_no);
            if(!"0".equals(payrecord.getStatus())){
                return "whzj/api/fail";
            }
            return "whzj/api/success";
        }catch (Exception e){
            return "whzj/api/fail";
        }


    }


    /**
     * 下载页面
     * @return
     */
    @RequestMapping("/download")
    public String download(ModelMap mmap, String userId)
    {
        WhUser user = whUserService.selectWhUserById(userId);
        if(user != null){
            mmap.put("code", user.getInvitationCode());
        }else{
            mmap.put("code", "111111");
        }

        return "whzj/api/download";
    }

    /**
     * 拉新分享页面
     * @return
     */
    @RequestMapping("/downloadNew")
    public String downloadNew(ModelMap mmap, String userId)
    {
        WhUser user = whUserService.selectWhUserById(userId);
        if(user != null){
            mmap.put("code", user.getInvitationCode());
        }else{
            mmap.put("code", "111111");
        }

        return "whzj/api/download_new";
    }

    /**
     * 用户服务协议
     * @return
     */
    @RequestMapping("/userAgreement")
    public String userAgreement(Model model)
    {
        WhzjBaseconfig baseconfig = whzjBaseconfigService.selectWhzjBaseconfigById("1");
        model.addAttribute("content", baseconfig.getUserAgreement());
        return "whzj/api/userAgreement";
    }

    @RequestMapping("/testPay")
    @ResponseBody
    public AjaxResult testPay(String type)throws Exception
    {


        String out_trade_no = "201608061511149";
        String notify_url = "http://www.baidu.com";
        String return_url = "http://www.baidu.com/aaa";
        String name = "test";
        String money = "0.01";
        String sign_type = "MD5";
//        String sitename = "tastaa";

        SortedMap<Object,Object> parameters= getSortedMapAli(pid,out_trade_no,notify_url,return_url,name,money, type);
        String sign = createSign("UTF-8", parameters);


        return success("操作成功", sign);

    }



    public static SortedMap<Object,Object>  getSortedMapAli(String pid,String out_trade_no,String notify_url,String return_url,
                                                            String name,String money,String type)throws Exception{
        SortedMap<Object,Object> parameters = new TreeMap<Object,Object>();
        parameters.put("pid", pid);
        parameters.put("out_trade_no", out_trade_no);
        parameters.put("notify_url", notify_url);
        parameters.put("return_url", return_url);
        parameters.put("name", name);
        parameters.put("money", money);
//        parameters.put("sign_type", sign_type);
        parameters.put("type", type);
//        parameters.put("sitename", sitename);

        return parameters;
    }


    public static String createSign(String characterEncoding,SortedMap<Object,Object> parameters)throws Exception{
        StringBuffer sb = new StringBuffer();
        Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序（升序）
        Iterator it = es.iterator();
        while(it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            Object v = entry.getValue();
            if(null != v && !"".equals(v)
                    && !"sign".equals(k) && !"key".equals(k)) {
                sb.append(k + "=" + v + "&");
            }
        }
        String _sb = sb.substring(0, sb.length()-1);
//        sb.append("key=").append("ocBsyVnhTNqbQpZPyaptSCOEmBPAwOYm");
//        String _sb = sb.substring(0, sb.length()-1);
        _sb += key;
//        sb.append("ocBsyVnhTNqbQpZPyaptSCOEmBPAwOYm");
        System.out.println("字符串拼接后是："+_sb);

        String sign = MD5(_sb).toLowerCase();
        return sign;
    }

    /**
     * 生成 MD5
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String MD5(String data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(data.getBytes());
//        byte[] array = md.digest(data.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }

}

